<!--
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2022-12-02 18:34:49
 * @LastEditors: Andy
 * @LastEditTime: 2023-03-28 16:07:56
-->
<template>
  <x-page class="flex-row">
    <div class="left-panel">
      <div class="top flex-row">
        <el-dropdown @command="handleCommand" v-hasPermi="['upms:dept:add']">
          <el-button type="primary" plain>
            {{ $t('organization.dept.add') }}<em class="el-icon-arrow-down el-icon--right"></em>
          </el-button>
          <el-dropdown-menu>
            <el-dropdown-item command="a">{{ $t('organization.dept.addRoot') }}</el-dropdown-item>
            <el-dropdown-item command="b">{{ $t('organization.dept.new') }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <div class="tree-container">
        <div class="label flex-row">
          <!-- <span>组织：</span> -->
        </div>
        <div class="search-input-container">
          <el-input prefix-icon="el-icon-search" :placeholder="$t('common.treeFilter')" v-model="filterText" clearable>
          </el-input>
          <depart-org-swtich
            ref="swtichOrgComponents"
            :options="orgTreeData"
            :current-org="currentOrg"
            @handleResetOrg="handleResetOrg"
          />
        </div>

        <el-scrollbar
          style="height: calc(100% - 60px)"
          v-loading="treeLoading"
          :element-loading-text="$t('common.loading')"
          element-loading-spinner="el-icon-loading"
        >
          <el-tree
            :props="treeProps"
            ref="tree"
            node-key="id"
            default-expand-all
            :key="treeKey"
            :data="deptTreeData"
            :expand-on-click-node="false"
            :highlight-current="true"
            :render-content="renderContent"
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
          ></el-tree>
        </el-scrollbar>
      </div>
    </div>
    <div class="right-panel">
      <div class="info-hearder flex-column">
        <div class="h3" v-if="currentNode?.deptName">
          <span>{{ currentNode?.deptName ?? '' }}</span>
          <el-button
            round
            size="small"
            v-hasPermi="['upms:dept:update']"
            @click="handleAddDept(currentNode)"
            style="margin-left: 8px"
            v-if="currentNode?.deptCode"
          >
            {{ $t('common.edit') }}
          </el-button>
          <el-button
            round
            size="small"
            v-hasPermi="['upms:dept:delete']"
            @click="handleDeletProm(currentNode)"
            style="margin-left: 8px"
            v-if="currentNode?.deptCode"
          >
            {{ $t('common.delete') }}
          </el-button>
        </div>
        <el-breadcrumb separator-class="el-icon-arrow-right" v-if="currentNode?.path" class="sub-title">
          <el-breadcrumb-item v-for="(ele, eleIndex) in currentNode.path" :key="eleIndex">{{ ele }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <h4 class="sub_title">
        <em class="iconfont icon-a-Property1zuzhipeizhi"></em>
        {{ $t('organization.dept.subDept') }}
      </h4>
      <!-- <el-alert :title="$t('organization.post.postInfoTips')"
                type="info"
                show-icon
                style="margin-bottom: 10px;">
      </el-alert> -->
      <!--数据面板-->
      <x-data>
        <!--数据面板按钮插糟-->
        <template #tool>
          <el-row type="flex" class="tools" justify="space-between">
            <el-col :span="18">
              <el-button
                v-hasPermi="['upms:dept:add']"
                v-if="currentNode?.deptName"
                round
                size="small"
                @click="
                  handleAddDept({
                    parentId: currentNode?.id ?? '0',
                    orgId: currentOrg.value
                  })
                "
              >
                {{ $t('organization.dept.new') }}
              </el-button>
              <el-button
                v-hasPermi="['upms:dept:exportExcel']"
                v-if="currentNode?.deptName"
                round
                size="small"
                @click="handleExportDept()"
              >
                {{ $t('common.export') }}
              </el-button>
            </el-col>
            <el-col :span="6" class="tools-config">
              <x-column-config :columns="columns" @updateColumns="updateColumns" @on-refresh="loadData" />
            </el-col>
          </el-row>
        </template>
        <x-table
          ref="tableCom"
          :pagination="pagination"
          :data-source="tableData"
          :loading="loading"
          :row-key="'id'"
          @on-change="handleTableChange"
        >
          <el-table-column
            v-for="(item, index) in tableColumns"
            :key="index"
            :prop="item.prop"
            :fixed="item.fixed"
            :show-overflow-tooltip="true"
            :width="item.width"
            :min-width="item.minWidth || '-'"
            :label="item.label"
            :sortable="'custom'"
          >
            <template #default="scope">
              <el-switch
                v-if="item.prop === 'state'"
                :value="scope.row[item.prop]"
                @change="handleChangeState(scope.row[item.prop], scope.row.id)"
                active-color="#4474F6"
                inactive-color="#A5A9B2"
                :disabled="!checkBntPermi('upms:dept:state')"
                :active-value="1"
                :inactive-value="0"
              ></el-switch>
              <span v-else> {{ scope.row[item.prop] | emptyVal }} </span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" :label="$t('common.opeartion')" :align="'center'" width="160">
            <template #default="scope">
              <more-table-actions
                :action-list="actions"
                :permis-list="permissionsActions"
                :row="scope.row"
                @onActionClick="handleActions"
              />
            </template>
          </el-table-column>
        </x-table>
      </x-data>
    </div>
    <department-add
      ref="departAddComponent"
      :dict-options="dictOptions"
      :org-id="currentOrg?.value ?? ''"
      :defaultDeptProps="treeProps"
      @handleSuccess="loadTreeData"
      @on-delete="handleDeleteDept"
    ></department-add>
  </x-page>
</template>
<script lang="jsx">
  import { TableListMixin, QueryDictMixin, PermissionsMixin } from '@package/utils'
  import { mapState } from 'pinia'
  import { pinias } from '@/common/pinia'
  import DepartmentAdd from '../components/departmentAdd.vue'
  import DepartOrgSwtich from '../components/departOrgSwtich.vue'
  import { columns, actions } from '../config/deptConfig'
  import {
    apiDeleteDept,
    apiPostOrganizTree,
    apiPostDeptTree,
    deptPageListUrl,
    apiPutEnableDept,
    apiPutDisbleDept,
    deptExportUrl
  } from '../api'
  import { EnumApiCode } from '../../../../../../globalEnum.js'

  const { cachedView } = pinias
  export default {
    name: 'Department',
    components: {
      DepartmentAdd,
      DepartOrgSwtich
    },
    mixins: [TableListMixin, QueryDictMixin, PermissionsMixin],
    data() {
      return {
        columns,
        actions,
        deptPageListUrl,
        deptExportUrl,
        filterText: '',
        isExpanded: false,
        disableMixinCreated: true,
        creatFlage: false,
        currentNode: null,
        treeLoading: true,
        allTreeData: [],
        deptTreeData: [],
        treeProps: {
          label: 'deptName',
          value: 'id',
          children: 'children'
        },
        treeKey: '1',
        orgTreeData: [],
        currentOrg: {},
        dictKeys: ['system.state']
      }
    },
    computed: {
      ...mapState(cachedView, ['visitedViews']),
      listUrl() {
        return this.deptPageListUrl
      },
      otherParam() {
        return { parentId: this.currentNode?.id ?? '' }
      }
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val)
      }
    },
    mounted() {
      this.creatFlage = true
      this.loadOrgTreeData()
      this.initDictConfig()
    },
    activated() {
      const temp = this.visitedViews.filter((v) => v.path === this.$route.path)
      if (this.disableMixinCreated && this.creatFlage && !temp) {
        this.loadOrgTreeData()
      }
    },
    methods: {
      async loadTreeData() {
        try {
          this.treeLoading = true
          const { data, code, msg } = await apiPostDeptTree({ orgId: this.currentOrg.value })
          this.treeLoading = false
          if (code === EnumApiCode.Success) {
            this.deptTreeData = data
            if (!this.currentNode?.id && this.deptTreeData?.length) {
              this.currentNode = this.deptTreeData[0]
            }
            this.treeKey = Math.random()
            if (this.currentNode?.id) {
              this.$nextTick(() => {
                this.refrenTreeCurrent(this.currentNode.id)
              })
            }
          } else {
            this.$message.error(msg)
          }
        } finally {
          this.treeLoading = false
        }
      },
      refrenTreeCurrent(key) {
        const isCheck = this.$refs.tree.getNode(key)
        if (!isCheck) {
          this.currentNode = this.deptTreeData[0]
        }
        this.$refs.tree.setCurrentKey(this.currentNode.id)
        const data = this.$refs.tree.getCurrentNode()
        const node = this.$refs.tree.getNode(this.currentNode.id)
        this.handleNodeClick(data, node)
      },
      handleResetOrg(val) {
        this.currentOrg = val
        this.currentNode = null
        this.loadTreeData()
      },
      loadOrgTreeData() {
        apiPostOrganizTree().then(({ code, data }) => {
          if (code === EnumApiCode.Success) {
            this.orgTreeData = JSON.parse(
              JSON.stringify(data)
                .replace(/orgName/g, 'label')
                .replace(/id/g, 'value')
            )
            if (this.orgTreeData?.length) {
              this.currentOrg = this.orgTreeData[0]
              this.loadTreeData()
            }
          }
        })
      },
      handleCommand(command) {
        if (command === 'a') {
          this.$refs.departAddComponent.handleOpen({ parentId: 0 }, false)
        } else if (command === 'b') {
          this.$refs.departAddComponent.handleOpen({ parentId: this.currentNode.id })
        }
      },
      filterNode(value, data) {
        if (!value) return true
        return data[this.treeProps.label].indexOf(value) !== -1
      },
      renderContent(h, { node, data, store }) {
        let nodeClass = ''
        if (data.state === 0) {
          nodeClass = 'gray'
        }
        return (
          <div class="custom-tree-node">
            <span class={nodeClass} title={node.label}>
              {node.label}
            </span>
          </div>
        )
      },
      handleNodeClick(data, node, ele) {
        this.currentNode.path = []
        this.currentNode = data
        if (node.parent.data?.id) {
          this.currentNode.path = [node.parent.data.deptName, this.currentNode.deptName]
        }
        this.handleSearch()
      },
      async handleChangeState(state, id) {
        const { code } = state === 1 ? await apiPutDisbleDept(id) : await apiPutEnableDept(id)
        if (code === EnumApiCode.Success) {
          this.$message.success(this.$t('system.user.successTips'))
          this.handleSearch()
        } else {
          this.$message.error(msg)
        }
      },
      handleAddDept(info) {
        this.$refs.departAddComponent.handleOpen(info)
      },
      handleExportDept() {
        this.handleExport(this.deptExportUrl)
      },
      handleActions({ key, data }) {
        switch (key) {
          case 'edit': // 修改岗位基本信息
            this.$refs.departAddComponent.handleOpen(data)
            break
          case 'delete':
            this.$confirm(this.$t('system.user.deleteSure'), this.$t('system.user.deletePrompt'), {
              confirmButtonText: this.$t('common.confirm'),
              cancelButtonText: this.$t('common.cancel'),
              type: 'warning'
            })
              .then((confirm) => {
                this.handleDeletProm(data)
              })
              .catch((cancel) => {})
            break
        }
      },
      handleDeletProm(data) {
        this.$confirm(this.$t('system.user.deleteSure'), this.$t('system.user.deletePrompt'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        })
          .then((confirm) => {
            this.handleDeleteDept(data.id)
          })
          .catch((cancel) => {})
      },
      /**
       * 删除部门的请求
       * @param deptId 部门ID string
       */
      async handleDeleteDept(deptId) {
        const { code, msg } = await apiDeleteDept(deptId)
        if (code === EnumApiCode.Success) {
          this.$message.success(this.$t('system.user.successTips'))
          this.loadTreeData(false)
        } else {
          this.$message.error(msg)
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import '../../../common/assets/style/variables';

  .flex-row {
    display: flex;
    flex-direction: row;

    .left-panel {
      flex: 1;
      min-width: 300px;
      border-radius: 3px;
      background-color: $x-default-bg-color;

      .top {
        margin-bottom: 16px;
        padding: 12px 15px;
        border-bottom: 1px solid #e0e0e0;
      }

      .tree-container {
        height: calc(100% - 100px);
        .search-input-container {
          padding: 0 15px;
        }
      }
    }

    .right-panel {
      display: flex;
      flex: 5;
      flex-direction: column;
      max-width: calc(100% - 300px);
      margin-left: 10px;
      color: #424242;
      border-radius: 3px;
      background-color: $x-default-bg-color;

      h4,
      .h3 {
        font-size: 20px;
        font-weight: 500;
        margin: 0;
        // padding: 0 20px;

        span {
          line-height: 30px;
        }
      }

      h4 {
        margin-bottom: 19px;
        padding: 0 20px;

        .iconfont {
          font-size: 20px;
        }
      }

      h3 {
        padding-top: 20px;
      }

      .el-breadcrumb.sub-title {
        font-size: 14px;
        line-height: 36px;
        padding-left: 7px;
      }

      .x-data-view {
        margin-top: 0;
        padding-top: 0;
        border-width: 0;
      }

      .tools {
        line-height: 42px;
        padding: 0 15px;
        border-radius: 3px;
        background-color: #eceff4;
      }

      .info-container {
        padding: 0 15px;
      }

      .info-hearder {
        font-size: 16px;

        // line-height: 60px;

        // margin-bottom: 10px;
        padding: 15px;
        color: $x-item-text-color;

        // border-bottom: 1px solid #e0e0e0;

        .el-icon-edit-outline {
          font-size: 18px;
          vertical-align: middle;
        }
      }
    }
  }
</style>
<style lang="scss">
  /* element滚动条组件 隐藏水平滚动条 */
  .tree-container .el-scrollbar__view {
    padding: 0 15px;
  }
  .tree-container .el-scrollbar__wrap {
    overflow-x: hidden;
  }

  .is-horizontal {
    display: none;
  }
</style>
